import axios from 'axios'
import router from '@/router'
import {
  Message
} from 'element-ui'
// create an axios instance
console.log(process.env.VUE_APP_BASE_API);
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 地址在.env开头的文件中
  timeout: 50000 // 请求超时时间（毫秒）
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers.token = localStorage.getItem('token')
    config.headers.vipid = localStorage.getItem('vipid')
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    //如果返回失效则提示重新登陆并返回登陆页面
    if (typeof res == "string") {
      if (res.indexOf("登陆失效") != -1) {
        localStorage.removeItem('hasLogin')
        localStorage.removeItem('vip')
        localStorage.removeItem('token')
        localStorage.removeItem('userInfo')
        Message({
          message: "登陆失效，请重新登陆", //.message,
          type: 'error',
          duration: 2 * 1000
        })
        return router.push(`/login`)
      }
    }

    return res
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error, //.message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service.request
